import { createRouter, createWebHistory, useRouter } from 'vue-router'
import IndexView from '@/views/IndexView.vue'
import LoginVue from '@/views/LoginVue.vue'
import MainView from '@/views/MainView.vue'
import SortView from '@/views/SortView.vue'
import CartView from '@/views/CartView.vue'
import UserInfoView from '@/views/UserInfoView.vue'
import OrderView from '@/views/OrderView.vue'
import InfoView from '@/views/InfoView.vue'
import UpdatePwd from '@/views/UpdatePwd.vue'
import InfoShowView from '@/views/InfoShowView.vue'
import CreateOrderView from '@/views/CreateOrderView.vue'
import { ElMessage } from 'element-plus'
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path:'/',
      component:IndexView,
      children:[
        {
          path:'',
          name:'main',
          component:MainView,
        },{
          path:'sort',
          name:'sort',
          component:SortView
        }
      ]
    },{
      path:'/login',
      name:'login',
      component:LoginVue
    },{
      path:'/cart',
      name:'cart',
      component:CartView,
      meta:{title:'购物车',auth:true}
    },{
      path:'/userInfo',
      name:'userInfo',
      component:UserInfoView,
      meta:{title:'个人中心',auth:true},
      children:[
        {
          path:'/info',
          name:'info',
          component:InfoView
        },{
          path:'/updatePwd',
          name:'updatePwd',
          component:UpdatePwd
        },{
          path:'/infoShow',
          name:'infoShow',
          component:InfoShowView
        }
      ]
    },{
      path:'/order',
      name:'order',
      component:OrderView,
      meta:{title:'购物车',auth:true}
    },
    {
      path:'/createOrder/:userId/:flowerIds',
      name:'createOrder',
      component:CreateOrderView,
      meta:{title:'创建订单',auth:true}
    }
  ],

})
import { useLoginStore } from '@/stores/LoginStore'
//定义全局路由守卫  - 前置路由守卫
router.beforeEach((to,from)=>{
  console.log('全局路由守卫')

  let loginStore = useLoginStore()

  if(to.meta.auth){
    if(loginStore.loginToken){
      return true
    }else{
      ElMessage({
        message: 'sorry,请先登录',
        type: 'error'
      })
      router.push('/login')
      return false
    }
  }
  return true;//允许路由跳转

})

//定义全局路由守卫  - 后置路由守卫
router.afterEach((to,from)=>{
  console.log('后置路由守卫')
  console.log(to)
  console.log(from)
  //修改页面标题
  document.title = (to.meta.title || '欢迎' ) as string
  return true;
})

export default router
